package com.lanou.lenanapp.volley;




import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.lanou.lenanapp.base.BaseApplication;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by dllo on 16/1/16.
 * 单例模式
 */
public class VolleySingleton {
    //声明类本身的一个静态对象
    private static VolleySingleton instance;
    //声明队列的对象
    private RequestQueue queue;
    private ImageLoader imageLoader;//图片

    //构造方法私有防止外部类 new 此对象
    private VolleySingleton() {
        //初始化队列
        queue = getQueue();
        imageLoader = new ImageLoader(queue, new com.lanou.lenanapp.volley.DoubleCache());

    }

    //公布一个静态方法，用于获取本类的实例
    public static VolleySingleton getInstance() {
        if (instance == null) {
            //同步代码块，防止多线程同时执行
            synchronized (VolleySingleton.class) {
                if (instance == null) {
                    instance = new VolleySingleton();
                }
            }
        }
        return instance;
    }
    //获取 RequestQueue实例的方法
    private RequestQueue getQueue(){
        if (queue == null) {
            //防止 Activity 的 Context 一直被占用
            queue = Volley.newRequestQueue(BaseApplication.getContext());
        }
        return queue;
    }
    //定义一个默认人的 Request 的 tag
    public static final String TAG = "VolleySingleton";
    public <T> void addRequest(Request<T> request){
        request.setTag("TAG");
        queue.add(request);
    }
    //重载一个方法，给 Request 添加自定义的 tag
    public <T> void addRequest(Request<T> request,Object tag){
        request.setTag("TAG");
        queue.add(request);
    }
    public void addStringRequest(String url,Response.Listener listener,
                                 Response.ErrorListener error){
        StringRequest stringRequest = new StringRequest(url,listener,error){
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("Accept-Encoding", "");
                return map;
            }
        };
        addRequest(stringRequest);

    }
    //将 Request 从 RequestQueue 中移除，取消网络请求
    public void  removeRequest(Object tag){
        queue.cancelAll(tag);
    }
    public ImageLoader getImageLoader(){
        return  imageLoader;
    }



}
